package org.example;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Test5 {
    //leetcode 637 二叉树的层平均值 https://leetcode.cn/problems/average-of-levels-in-binary-tree/description/
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> ret = new ArrayList<>();
        if (root == null) return ret;
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.add(root);
        while (!deque.isEmpty()) {
            int count = deque.size();
            int num = count;
            long sum = 0;
            while (count > 0) {
                TreeNode tmp = deque.poll();
                if (tmp.left != null) deque.add(tmp.left);
                if (tmp.right != null) deque.add(tmp.right);
                sum += tmp.val;
                count--;
            }
            ret.add(sum * 1.0 / num);
        }
        return ret;
    }
}
